package fox.framework.rpc.converter;

import fox.framework.rpc.exception.RpcConverterException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cuichao
 * @Description: RpcMessageConverters
 * @Date: create in 2021/1/31 20:28
 */
public class RpcMessageConverters {

    private final List<RpcMessageConverter> converters = new ArrayList<>();

    private final Map<String, RpcMessageConverter> converterMap = new ConcurrentHashMap<>();


    public RpcMessageConverters(List<RpcMessageConverter> converters) {
        addConverters(converters);
    }

    public RpcMessageConverter get(String name) {
        return converterMap.getOrDefault(name, null);
    }

    public RpcMessageConverter getSupportConverter(String protocol, String mediaType) {

        for (RpcMessageConverter converter : converters) {
            if (converter.hasSupport(protocol, mediaType)) {
                return converter;
            }
        }
        return processNoSupportConverter(mediaType);
    }


    protected RpcMessageConverter processNoSupportConverter(String mediaType) {
        String msg = String.format("request content-type: %s is not support", mediaType);
        throw new RpcConverterException(msg);
    }


    private void addConverters(List<RpcMessageConverter> converters) {
        this.converters.addAll(converters);
        converters.forEach(v -> converterMap.put(v.getConverterName(), v));
    }

}
